package xyz.weblade.lynchmybatis.config;

import org.apache.ibatis.executor.statement.StatementHandler;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Signature;
import org.apache.ibatis.reflection.MetaObject;
import org.apache.ibatis.reflection.SystemMetaObject;

import java.sql.Connection;
import java.util.Properties;

/**
 * @author lynch
 * @since 2025/5/8 v1.0
 * SQL执行时间统计插件
 */
@Intercepts({
        @Signature(type = StatementHandler.class, method = "prepare", args = {Connection.class,Integer.class})
}
)
public class SQLTimeCostPlugin implements Interceptor {
    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        long startTime = System.currentTimeMillis();

        // 执行原方法
        Object result = invocation.proceed();

        long endTime = System.currentTimeMillis();
        long executeTime = endTime - startTime;

        // 获取SQL语句
        MetaObject metaObject = SystemMetaObject.forObject(invocation.getTarget());
        String sql = (String) metaObject.getValue("delegate.boundSql.sql");

        // 打印SQL语句及执行时间
        System.out.println("Executed SQL: " + sql);
        System.out.println("Execution Time: " + executeTime + " ms");

        return result;
    }

    @Override
    public Object plugin(Object target) {
        return Interceptor.super.plugin(target);
    }

    @Override
    public void setProperties(Properties properties) {
        Interceptor.super.setProperties(properties);
    }
}
